package com.example.maax.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.example.maax.entity.User;
import com.example.maax.mapper.UserMapper;
import com.example.maax.vo.UserReqVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserMapper userMapper;

    @GetMapping
    public Object list() {
        return JSON.toJSONString(userMapper.selectList(null));
    }

    @PostMapping
    public void create(@RequestBody UserReqVO reqVO) {
        if (ChainWrappers.lambdaQueryChain(userMapper)
                .eq(User::getCode, reqVO.getCode())
                .exists()) {
            throw new ResponseStatusException(400, "code重复", null);
        }

        userMapper.insert(UserReqVO.convert(reqVO));
    }

    @PutMapping("/{id}")
    public void update(@PathVariable Long id, @RequestBody UserReqVO reqVO) {
        if (ChainWrappers.lambdaQueryChain(userMapper)
                .eq(User::getCode, reqVO.getCode())
                .ne(User::getId, id)
                .exists()) {
            throw new ResponseStatusException(400, "code重复", null);
        }

        User user = UserReqVO.convert(reqVO);
        user.setId(id);
        userMapper.updateById(user);
    }

    @DeleteMapping("/{code}")
    public void delete(@PathVariable String code) {
        ChainWrappers.lambdaUpdateChain(userMapper)
                .eq(User::getCode, code)
                .remove();
    }
}
